<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute,useRouter } from 'vue-router'
import { jwtDecode } from 'jwt-decode';

interface Article {
    id: number
    name: string
    content: string
    cover: string
    author: string
    pub_date: string
}
const router = useRouter()
const route = useRoute()
const article = ref<Article | null>(null)
const relatedArticles = ref<Article[]>([])
const loading = ref(false)
const error = ref('')
const username = ref<string | null>(null)
const avatar = ref<string | null>(null)

const navigationItems = [
    { name: '问医生', link: '/sections' },
    { name: '查疾病', link: '/disease' },
    { name: '查药品', link: '/medicine' },
    { name: '查医院', link: '/hospital' },
    { name: '查检查/手术', link: '/examination' },
    { name: '查疫苗', link: '/vaccine' },
    { name: '急救指南', link: '/emergency' },
    { name: '测一测', link: '/test' },
    { name: '科普视频', link: '/videos' }
]

const fetchArticleDetail = async () => {
    loading.value = true
    error.value = ''

    try {
        const response = await fetch(`http://127.0.0.1:8000/disease/detail/${route.params.articleId}/`)
        if (!response.ok) {
            throw new Error('获取文章详情失败')
        }
        article.value = await response.json()
    } catch (err) {
        error.value = err instanceof Error ? err.message : '发生错误'
        console.error('获取文章错误:', err)
    } finally {
        loading.value = false
    }
}

const fetchRelatedArticles = async () => {
    try {
        const response = await fetch(`http://127.0.0.1:8000/disease/related/${route.params.articleId}/`)
        if (!response.ok) {
            throw new Error('获取相关文章失败')
        }
        relatedArticles.value = await response.json()
    } catch (err) {
        console.error('获取相关文章错误:', err)
    }
}





const fetchUserInfo = async () => {
    const token = localStorage.getItem('token');
    if (token) {
        const payload = ref<any>(jwtDecode(token));
        username.value = payload.value.username;
        avatar.value = 'http://127.0.0.1:8000/uploads/' + payload.value.avatar;
        console.log(avatar.value);
    }

}

const logout = () => {
    localStorage.removeItem('token');
    username.value = null;
    avatar.value = null;
};


onMounted(() => {
    fetchArticleDetail()
    fetchUserInfo()
    fetchRelatedArticles()
    
})
</script>

<template>
    <div class="min-h-screen flex flex-col">
        <!-- Header -->
        <header class="header bg-white p-4 shadow-md flex justify-between items-center">

            <div class="container flex items-center">
                <div class="links-container">
                    <a href="#" class="flex items-center text-gray-600 hover:text-blue-500">
                        <i class="icon-download"></i>
                        <span class="ml-1">下载App</span>
                    </a>
                    <a href="#" class="text-blue-500 font-bold hover:underline">栏目收费说明</a>
                </div>
                <!-- 使用 v-if/v-else 来条件渲染登录/注册按钮或用户信息 -->
                <div v-if="!username" class="lrcs items-center space-x-4"> <!-- Flex 布局让内容一行排列 -->
                    <RouterLink class="btn-login"
                        :to="{ name: 'Login', query: { redirecturl: router.currentRoute.value.fullPath } }">登录
                    </RouterLink>
                    <RouterLink class="btn-register" to='/register'>注册</RouterLink>
                </div>
                <div v-else class="user-info flex items-center space-x-3"> <!-- 用户信息 -->
                    <img :src="avatar" alt="用户头像" class="user-avatar w-8 h-8 rounded-full" />
                    <span>{{ username }}</span>
                    <span class="text-logout" @click="logout">退出</span>
                </div>

            </div>
        </header>

        <!-- Search -->
        <div class="search-header">
            <div class="search-wrapper">
                <h1 class="text-a">丁香医生</h1>
                <input type="text" v-model="searchQuery" placeholder="搜索疾病、医院、药品" class="search-input" />
                <button class="search-button">搜索</button>
            </div>
        </div>

        <!-- Navigation -->
        <nav class="main-nav">
            <router-link v-for="item in navigationItems" :key="item.name" :to="item.link" class="nav-link">
                {{ item.name }}
            </router-link>
        </nav>

        <main class="container mx-auto px-4 py-8">
            <div v-if="loading" class="text-center py-10">
                加载中...
            </div>

            <div v-else-if="error" class="text-center py-10 text-red-500">
                {{ error }}
            </div>

            <article v-else-if="article" class="max-w-3xl mx-auto bg-white rounded-lg shadow-md p-8">
                <h1 class="text-3xl font-bold text-gray-900 mb-4">{{ article.name }}</h1>

                <!-- 交换发布时间和作者的位置，增加间距 -->
                <div class="flex gap-4 text-gray-600 text-sm mb-6">
                    <span>{{ article.pub_date }}</span>
                    <span class="custom-margin">作者：{{ article.author }}</span>
                </div>

                <!-- 调整图片大小，使其适合内容框 -->
                <div class="image-container">
                    <img v-if="article.cover" :src="article.cover" :alt="article.name" class="content-image">
                </div>
                <!-- 添加自定义类名以设置首行缩进 -->
                <div class="prose max-w-none text-indent-custom" v-html="article.content"></div>
            </article>
            <!-- 相关文章部分 -->
            <div v-if="relatedArticles.length > 0" class="related-articles-section mt-8">
                <h2 class="text-2xl font-bold mb-6">相关文章</h2>
                <div class="grid gap-4">
                    <router-link v-for="relatedArticle in relatedArticles" :key="relatedArticle.id"
                        :to="`/message/${relatedArticle.id}`" class="related-article-card" target="_blank"
                        rel="noopener noreferrer">
                        <div class="related-article-image">
                            <img :src="relatedArticle.cover || '/default-cover.jpg'" :alt="relatedArticle.name">
                        </div>
                        <div class="related-article-content">
                            <h3 class="related-article-title">{{ relatedArticle.name }}</h3>
                            <div class="related-article-text" v-html="relatedArticle.content"></div>
                        </div>
                    </router-link>
                </div>
            </div>


        </main>

        <!-- Footer -->
        <footer class="mt-auto">
            <div class="bottom-links">
                <a target="_blank" href="http://www.dxy.cn/pages/copyright.html" rel="nofollow">版权声明</a>
                <a target="_blank" href="https://dxy.com/column/board" rel="nofollow">作者编委</a>
                <a target="_blank" href="https://ask.dxy.com/ama/index" rel="nofollow">丁香医生</a>
                <a href="mailto:doctor@dxy.com" rel="nofollow">投稿邮箱 doctor@dxy.com</a>
                <a target="_blank">客服电话：0571-22931767</a>
            </div>
        </footer>
    </div>
</template>

<style scoped>
/* 登录 */
.header {
    background-color: #f7f7f7;
    color: rgba(0, 0, 0, 0.5);
    box-shadow: 0 3px 3px rgba(0, 0, 0, 0.1);
    padding: 16px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
}

.header a {
    /* a标签默认有下划线，删除下划线 */
    text-decoration: none;
    /* 字体颜色 */
    color: #666;
    /* 字体大小 */
    font-size: 14px;
    display: flex;
    align-items: center;
    /* 用于定义元素从一种样式过渡到另一种样式时的动画效果 */
    transition: color 0.3s ease;
}

.header a:hover {
    color: #00b38a;
    /* Match green color on hover */
}

.header a.text-blue-500 {
    color: #00b38a;
    /* Green color for special links */
    font-weight: bold;
    margin-left: 16px;
}

.text-logout {
    margin-left: 16px;
    background-color: transparent;
    /* 透明背景 */
    border: none;
    /* 无边框 */
    color: #666666;
    /* 文本颜色与下载链接一致 */
    padding: 0;
    /* 移除内边距 */
    font-size: 14px;
    font-weight: normal;
    /* 正常字体粗细 */
    cursor: pointer;
    text-decoration: none;
    /* 移除下划线 */
    transition: color 0.3s ease;
    /* 颜色过渡效果 */
}

.text-logout:hover {
    color: #00b38a;
    text-decoration: underline;

}

.container {
    display: flex;
    align-items: center;
    
    flex-wrap: wrap;

    gap: 16px;
    margin-left: 350px;
    margin-right: 350px;

}

/* 可以添加一个包含栏目、下载等链接的容器样式 */
.links-container {
    display: flex;
    align-items: center;
    /* 之间的间隔 */
    border: none;
}

.btn-login {
    background-color: transparent;
    /* 透明背景 */
    border: none;
    /* 无边框 */
    color: #666666;
    /* 文本颜色与下载链接一致 */
    padding: 0;
    /* 移除内边距 */
    font-size: 14px;
    font-weight: normal;
    /* 正常字体粗细 */
    cursor: pointer;
    text-decoration: none;
    /* 移除下划线 */
    transition: color 0.3s ease;
    /* 颜色过渡效果 */
}

.btn-register {
    background-color: transparent;
    /* 透明背景 */
    border: none;
    /* 无边框 */
    color: #666666;
    /* 文本颜色与下载链接一致 */
    padding: 0;
    /* 移除内边距 */
    font-size: 14px;
    font-weight: normal;
    /* 正常字体粗细 */
    cursor: pointer;
    text-decoration: none;
    /* 移除下划线 */
    transition: color 0.3s ease;
    /* 颜色过渡效果 */
    margin-left: 13px;
}

.lrcs {
    display: flex;
    align-items: center;

}

/* 添加伪类来模仿下载链接的hover效果 */
.btn-login:hover,
.btn-register:hover {
    color: #00b38a;
    /* 悬停时变为绿色 */
    text-decoration: underline;
    /* 悬停时添加下划线 */
}

/* User Info Styling */
.user-info {
    display: flex;
    align-items: center;
}

.user-info .user-avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    /* Circular avatar */
    object-fit: cover;

}

.user-info span {
    font-size: 14px;
    font-weight: 500;
    color: #333333;
}

/* --- */

.btn-primary {
    margin-right: 10px;
}
/* 作者和发布时间的距离 */
.custom-margin {
    margin-left: 20px;
    /* 或者您想要的任何大小，例如 2em, 3rem 等 */
}

/* 设置首行缩进的大小，例如2em */
.text-indent-custom {
    text-indent: 2em; /* 你可以根据需要调整这个值，比如使用 1.5em, 30px 等 */
}
/* 相关文章整体容器对齐主内容宽度 */
.related-articles-section {
    max-width: 800px;
    margin: 0 auto;
}
/* 相关文章部分两行两列 */
.related-articles-section .grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    /* 两列布局 */
    gap: 20px;
}

/* 修改相关文章卡片样式 */
.related-article-card {
    display: flex;
    align-items: center;
    gap: 16px;
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: transform 0.2s ease;
    width: 100%;
    text-decoration: none;
    /* 去除下划线 */
    color: inherit;
    /* 保持文字颜色 */
}

.related-article-card:hover {
    transform: translateY(-4px);
}

.related-article-image {
    width: 100px;
    height: 100px;
    flex-shrink: 0;
    border-radius: 8px;
    overflow: hidden;
}

.related-article-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.related-article-content {
    flex: 1;
}

.related-article-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin-bottom: 4px;
    line-height: 1.4;
}

.related-article-text {
    font-size: 14px;
    color: #666;
    line-height: 1.6;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}


/* 底部导航 */
.bottom-links {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 8px;
    padding: 24px;
    background-color: #f5f5f5;
}

.bottom-links a {
    color: #666;
    text-decoration: none;
    padding: 4px 8px;
}

/* 顶部导航 */
.main-nav {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 10px 0;
    background-color: #fff;
    border-bottom: 1px solid #eee;
}

.nav-link {
    padding: 6px 16px;
    color: #666;
    text-decoration: none;
    font-size: 14px;
    transition: color 0.2s;
}

.nav-link:hover {
    color: #00b38a;
}

/* 搜索 */
.text-a {
    font-size: 32px;
    font-weight: 700;
    color: #00b38a;
    margin: 0 auto;
    letter-spacing: 1px;
}

.search-header {
    background-color: #fff;
    padding: 20px 0;
}

.search-wrapper {
    max-width: 600px;
    margin: 0 auto;
    display: flex;
    gap: 10px;
}

.search-input {
    flex: 1;
    padding: 12px 20px;
    border: 2px solid #00b38a;
    border-radius: 24px;
    font-size: 16px;
    outline: none;
}

.search-button {
    padding: 12px 30px;
    background-color: #00b38a;
    color: white;
    border: none;
    border-radius: 24px;
    cursor: pointer;
    font-size: 16px;
}

/* 登录注册 */
.text-c {
    display: flex;
    justify-content: flex-end;
    width: 100%;
}

.btn {
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    background-color: #00b38a;
    color: white;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.btn:hover {
    background-color: #00b38a;
}

.btn:focus {
    outline: none;
}



/* 文章内容 */
/* 文章内容容器 */
article {
    max-width: 800px;
    margin: 0 auto;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    padding: 16px;
}

.article-header,
.article-content {
    padding: 16px;
}

.text-3xl {
    font-size: 1.875rem;
    color: #333;
}

/* 图片容器和样式 */
.image-container {
    display: flex;
    justify-content: center;
    margin-bottom: 1.5rem;
}

.content-image {
    max-width: 100%;
    max-height: 400px;
    width: auto;
    height: auto;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
</style>
